import time
import yaml 
import fcntl
import os
import atexit

class MyLog:
    def __init__(self,log_path,mode='cache'):
        self.path=log_path
        self.able=1
        self.cache=""
        self.mode=mode
        
        atexit.register(self._cleanup)  # 注册退出处理
    def _cleanup(self):
        """安全的退出处理方法"""
        print("Mylog Exit!")
        try:
            self.flush()
        except Exception as e:
            print(f"Cleanup failed: {e}")

    def open(self):
        self.f=open(self.path,'a')
    def close(self):
        self.f.close()

    def init(self,run_file="",description=""):
        self.write("-------------------------------------------",end="")
        self.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),end="")
        self.write("-------------------------------------------")
        self.desription_write(description)
        self.args_write()
        self.run_file_path_write(run_file)

    def desription_write(self,description=""):
        self.open()
        if description=="" and 'description' in self.config:
            self.write(f"Description: {self.config['description']}")
        elif description!="":
            self.write(f"Description: {description}")
        else:
            self.write("No description!")
        self.close()

    def args_write(self,yaml=1,**args):
        self.open()
        self.write("Args: ")
        if not yaml:
            for k in args.keys():
                if k!='description':
                    self.write(f"  {k}: {str(args[k])}")
        else:
            for k in self.config.keys():
                if k!='description':
                    self.write(f"  {k}: {str(self.config[k])}")
        self.close()

    def run_file_path_write(self, path):
        self.write("Script path: "+ path)

    def info_write(self,content):
        t=time.strftime("%H:%M:%S",time.localtime())
        self.write(f"[INFO {t}]{str(content)}")

    def flush(self):
        #将缓冲区内容写入文件
        with open(self.path, 'a+') as f:  # 使用 'a+' 模式追加读写
            fcntl.flock(f.fileno(), fcntl.LOCK_EX)  # 加锁
            f.seek(0)  # 移动指针到文件开头
            old = f.read()  # 读取旧内容
            f.seek(0)  # 重置指针
            f.truncate()  # 清空文件
            f.write(self.cache + old)  # 写入新内容+旧内容
            self.cache=''


    def write(self,content,end="\n"):
        if self.able:
            if self.mode=='cache':
                self.cache+=str(content)+end
            else:
                self.open()
                self.f.write(str(content)+end)
                self.close()

    def read_yaml(self,yaml_path):
        with open(yaml_path,'r') as f:
            self.config=yaml.load(f,Loader=yaml.FullLoader)
        return self.config.copy()

    def write_disable(self):
        self.able=0
    
    def write_enable(self):
        self.able=1

    def __del__(self):
        self.flush()